home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: Memory leakage
- Date: 19 Apr 1996 07:17:46 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4l7emq$a2n@sparcserver.lrz-muenchen.de>
- References: <4l3582$1v@alice.walrus.com>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- warrenj@walrus.com (Warren Johnson) writes:
-
- >Suppose I have a function:
-
- >int give_number() {
- > ...
- > ...
- > ...
- >}
-
- >and in main I have a line :
-
- >if(x>give_number()) {
- > ...
- > ... }
-
- >Now my question is this: give_number() returns an integer. Obviously
- >the compiler must allocate memory for this integer. However, we are not
- >returning this integer to an integer pointer, therefore this allocated
- >memory is floating about in the void somewhere without something pointing
- >to it.
-
- Consider evaluating this expression:
-
- int x, y = 42;
-
- x = 3 * y + 10;
-
- "3 * y" is evaluated first, the result is stored in a temporary variable
- that you will never see (well, in most implementations it will be stored
- in a register anyway), then 10 is added, and the result is stored in
- either the same or an other temporary variable that you will never see.
-
- >Is this memory deallocated when the function is finished running
- >it's course or do i have to do this:
-
- >y = give_number();
-
- >if(x>y) { blabalh}
-
- >free(y); // or just let y be deallocated when the function is over with
-
- This is a syntax error in C as it is defined today, but it may be a
- very dangerous expression if "//" will be accepted as a comment delimiter
- in a future version of the language definition.
-
- _Never_ pass something to free that is not a pointer value returned from
- a memory allocation function, i.e. from either malloc(), calloc() or
- realloc().
-
- You don't care about "deallocating" temporary variables that are used
- in the evaluation of "normal" expressions, so there is no need to
- care about temporary variables that are used to store the return
- value of a function.
-
- If your function returns a pointer to memory allocated in that function,
- you will have to think about freeing it if you do not need it any more.
-
- char *copyName(const char *name)
- {
- char *res;
-
- res = malloc(strlen(name) + 1);
- if (res)
- strcpy(res, name);
- return res;
- }
-
- In this case, the _caller_ of that function is responsible for
- deallocating the memory allocated in the function, but this is
- because the memory was _allocated in the function_.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
-